<?php
/**
 * @package     Joomla.Site
 * @subpackage  mod_articles_latest
 *
 * @copyright   Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

require_once JPATH_SITE . '/components/com_content/helpers/route.php';

JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_content/models', 'ContentModel');

abstract class ModLatestnewsHelper
{

    public static function getList(&$params)
    {

        // Get the dbo
        $db = JFactory::getDbo();

        // Set the filters based on the module params
        $start = 0;
        $limit = (int) $params->get('count', 8);

        $article_id = $params->get('article_id');
        if($article_id == 0)
            return null;

        //$params->get('article_view');
        //$params->get('article_option');

        $article_query = 'SELECT * FROM #__content WHERE id = '.$article_id;
        $article_obj = $db->setQuery($article_query)->loadObject();


        if($article_obj->id == 0)
            return null;

        // Category filter
        $category_id = $params->get('catid', array());


        //  Featured switch
        switch ($params->get('show_featured'))
        {
            case '1' :
                $featured = 'only';
                break;
            case '0' :
                $featured = 'hide';
                break;
            default :
                $featured =  'show';
                break;
        }


        // Set ordering
        $order_map = array(
            'm_dsc' => 'a.modified DESC, a.created',
            'mc_dsc' => 'CASE WHEN (a.modified = ' . $db->quote($db->getNullDate()) . ') THEN a.created ELSE a.modified END',
            'c_dsc' => 'a.created',
            'p_dsc' => 'a.publish_up',
            'random' => 'RAND()',
        );
        $ordering = JArrayHelper::getValue($order_map, $params->get('ordering'), 'a.publish_up');
        $dir      = 'DESC';

        $ordering = $ordering;
        $direction =  $dir;

        $query ="
        SELECT a.id, a.title, a.alias, a.introtext, a.fulltext, a.checked_out, a.checked_out_time, a.catid,
        a.created, a.created_by, a.created_by_alias,
        CASE WHEN a.modified = '0000-00-00 00:00:00' THEN a.created ELSE a.modified END as modified, a.modified_by,
        uam.name as modified_by_name,CASE WHEN a.publish_up = '0000-00-00 00:00:00' THEN a.created ELSE a.publish_up END as publish_up,a.publish_down,
        a.images, a.urls, a.attribs, a.metadata, a.metakey, a.metadesc, a.access, a.hits, a.xreference, a.featured,
        LENGTH(a.fulltext) AS readmore,CASE WHEN badcats.id is not null THEN 0 ELSE a.state END AS state,c.title AS category_title, c.path AS category_route,
        c.access AS category_access, c.alias AS category_alias,CASE WHEN a.created_by_alias > ' ' THEN a.created_by_alias ELSE ua.name END AS author,
        ua.email AS author_email,parent.title as parent_title, parent.id as parent_id, parent.path as parent_route, parent.alias as parent_alias,
        ROUND(v.rating_sum / v.rating_count, 0) AS rating, v.rating_count as rating_count,c.published,
        CASE WHEN badcats.id is null THEN c.published ELSE 0 END AS parents_published
		FROM #__content AS a
		LEFT JOIN #__content_frontpage AS fp ON fp.content_id = a.id
		LEFT JOIN #__categories AS c ON c.id = a.catid
		LEFT JOIN #__users AS ua ON ua.id = a.created_by
		LEFT JOIN #__users AS uam ON uam.id = a.modified_by
		LEFT JOIN #__categories as parent ON parent.id = c.parent_id
		LEFT JOIN #__content_rating AS v ON a.id = v.content_id
		LEFT OUTER JOIN (SELECT cat.id as id FROM #__categories AS cat JOIN #__categories AS parent ON cat.lft BETWEEN parent.lft AND parent.rgt WHERE parent.extension = 'com_content' AND parent.published != 1 GROUP BY cat.id ) AS badcats ON badcats.id = c.id
		WHERE CASE WHEN badcats.id is null THEN a.state ELSE 0 END = 1 ";

        if(count($category_id) > 0) {
            $query .=" AND a . catid IN(".implode(',',$category_id).")";
        }

		$query .=" AND (a.publish_up = '0000-00-00 00:00:00' OR a.publish_up <= '".date("Y-m-d H:i:s")."')
		AND (a.publish_down = '0000-00-00 00:00:00' OR a.publish_down >= '".date("Y-m-d H:i:s")."' OR a.publish_down < '".date("Y-m-d H:i:s")."')";
        //echo str_replace('#_','wphnew',$query);
        $query_older = $query;
        if(intval($article_obj->id) > 0) {

            $query .= " AND a.created > '" . $article_obj->created . "'";
            $query_older .= " AND a.created < '" . $article_obj->created . "'";
        }

		$query .=" ORDER BY ".$ordering." ".$direction." LIMIT 0, ".$limit;
        $query_older .= " ORDER BY ".$ordering." ".$direction." LIMIT 0, ".$limit;

        $sooner_obj = $db->setQuery($query)->loadObjectList();
        $older_obj = $db->setQuery($query_older)->loadObjectList();
        //$items = $model->getItems();

        if(count($sooner_obj) > 0) {
            foreach ($sooner_obj as &$item) {
                $item->slug = $item->id . ':' . $item->alias;
                $item->catslug = $item->catid . ':' . $item->category_alias;
                $item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
            }
        }

        if(count($older_obj) > 0) {
            foreach ($older_obj as &$item) {
                $item->slug = $item->id . ':' . $item->alias;
                $item->catslug = $item->catid . ':' . $item->category_alias;
                $item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
            }
        }
        $items = new stdClass();
        $items->sooner_obj = $sooner_obj;
        $items->older_obj = $older_obj;

        return $items;
    }
}
